<template>
  <div class="dashboard-container">
    <div
      class="demo-login-out"
      v-if="rname === 'ROLE_DEMO'"
      @click.stop.prevent="triggerLogout"
    >
      <i class="fa fa-power-off"></i>
    </div>
    <div class="dashboard-head">
      <div class="header_title">
        <h2 @click.stop.prevent="triggerAdmin" style="cursor:pointer;">
          {{ mainTitle }}
        </h2>
        <button
          v-if="!isChina"
          class="dashboard-button"
          @click="backToChina"
          title="返回上一层"
        >
          <i class="fa fa-mail-reply" aria-hidden="true"></i>
        </button>
      </div>
    </div>
    <div class="control-wrapper">
      <clock></clock>
      <h2 class="title">{{ isChina ? defaultTitle : cityInfo.areaName }}</h2>
      <p class="subtitle" v-if="!isChina">
        用电高峰时段<span>{{ cityInfo.peakHour }}</span>
      </p>
    </div>
    <div class="count-wrapper" v-if="!isChina">
      <div class="single-count">
        企业数<span>{{ !!companyList ? companyList.length : 0 }}</span
        >个
      </div>
      <div class="single-count">
        分路总数<span>{{ cityInfo.deviceTotal }}</span
        >个
      </div>
      <div class="single-count">
        今日异常事件<span>{{ cityInfo.errorNumber }}</span
        >起
      </div>
    </div>
    <div class="dashboard-left" v-if="!isChina">
      <LeftBlock :leftBockInfo="leftBockInfo" />
    </div>
    <div class="dashboard-right" v-if="!isChina">
      <RightBlock :rightBlockInfo="rightBlockInfo" />
    </div>
    <div class="dashboard-map" ref="dashboardMapRef" />
    <AllCityBar :hide="!isChina" />
  </div>
</template>

<script>
import LeftBlock from "./LeftBlock";
import RightBlock from "./RightBlock";
import AllCityBar from "./AllCityBar";
import "./index.scss";

import { mapMutations, mapState, mapActions, mapGetters } from "vuex";

import {
  getCompanyDetailByCompanyId,
  getGeoJson,
  getVideoCitys,
  getVideoCity
} from "@/api";
import { getToken } from "@/utils/storage";
import { config, allCitysPositons } from "./config";
import { cacheGeoJson, getCacheGeoJson } from "@/utils/storage";

const convertData = data => {
  let res = [];
  data.forEach(t => {
    let geoCoord = allCitysPositons[t.name];
    if (geoCoord) {
      res.push({
        name: t.name,
        value: allCitysPositons[t.name].concat(40)
      });
    }
  });
  return res;
};

const findChinaGeo = () => {
  return new Promise(resolve => {
    const result = getCacheGeoJson(100000);
    if (!result) {
      getGeoJson("100000_full").then(res => {
        const { data } = res;
        cacheGeoJson(100000, data);
        resolve();
      });
    } else {
      resolve();
    }
  });
};

const findCityGeo = (name, sysCode, cityGeo) => {
  return new Promise(resolve => {
    if (cityGeo) {
      resolve();
    } else {
      getGeoJson(`${sysCode}_full`).then(res => {
        const { data } = res;
        cacheGeoJson(name, data);
        resolve();
      });
    }
  });
};

let alarm = null;
export default {
  computed: {
    ...mapState({
      rname: state => state.userInfo.rname
    }),

    mainTitle() {
      return "用电安全物联网平台";
    }
  },
  mounted() {
    findChinaGeo().then(res => {
      this.drawChina();
    });
  },
  components: { LeftBlock, RightBlock, AllCityBar },
  data: () => ({
    defaultTitle: "",
    mapData: [],
    mapBottle: null,
    isChina: true,
    menuShow: false,
    cityList: [],
    companyList: [],
    leftBockInfo: {},
    rightBlockInfo: {},
    cityInfo: {}
  }),

  methods: {
    ...mapActions(["logout"]),
    ...mapMutations(["SET_COMPANYID"]),
    backToChina() {
      this.isChina = true;
      this.drawChina();
    },
    async drawChina() {
      const self = this;
      if (!this.echarts.getMap("china")) {
        const data = getCacheGeoJson(100000);
        self.echarts.registerMap("china", data);
      }
      const cityList = (this.cityList = (await getVideoCitys()).data);
      const option = { ...config };
      const resultSeries = convertData(cityList);
      const series = [
        {
          type: "effectScatter",
          coordinateSystem: "geo",
          zlevel: 2,
          rippleEffect: {
            brushType: "stroke"
          },
          showEffectOn: "emphasis",
          hoverAnimation: true,
          label: {
            normal: {
              show: true,
              position: "right",
              formatter: "{b}"
            }
          },
          symbolSize: function(val) {
            return val[2] / 2.5;
          },
          itemStyle: {
            normal: {
              color: "#F4E925"
            }
          },
          data: resultSeries,
          tooltip: {
            show: false
          }
        }
      ];
      option.geo.map = "china";
      option.geo.center = [106.971321312, 36.811312];
      option.geo.zoom = 2.3;
      option.geo.left = "20%";
      option.series = series;
      this.mapBottle = this.echarts.init(this.$refs.dashboardMapRef);
      this.mapBottle.setOption(option);
      window.addEventListener("resize", this.mapBottle.resize);
      this.mapBottle.off("click");
      this.mapBottle.on("click", params => {
        this.prepareCity(params.name);
      });
    },

    async prepareCity(name) {
      const singleCity = this.cityList.find(t => t.name === name);
      const singleCompany = this.companyList
        ? this.companyList.find(t => t.name === name)
        : false;
      const existMap = this.echarts.getMap(name);
      const cityGeo = getCacheGeoJson(name);
      if (!singleCity && !singleCompany) {
        return false;
      } else {
        if (existMap) {
          const { sysCode, id } = singleCity;
          this.printCity(name, id);
        } else {
          if (singleCity) {
            const { sysCode, id } = singleCity;
            await findCityGeo(name, sysCode, cityGeo);
            const geo = getCacheGeoJson(name);
            this.echarts.registerMap(name, geo);
            this.printCity(name, id);
          } else if (singleCompany) {
            const { id } = singleCompany;
            getCompanyDetailByCompanyId(id).then(res => {
              const row = res.data;
              if (res.code === 200) {
                if (this.rname === "ROLE_DEMO") {
                  this.SET_COMPANYID(id);
                  this.$router.push("/datacenter");
                } else {
                  const { transformerStructure, id } = row;
                  if (transformerStructure) {
                    const urlOnline = `http://pht.bjsdzk.com?token=${getToken()}&companyId=${
                      row.id
                    }`;
                    window.open(urlOnline, "_blank");
                  } else {
                    this.SET_COMPANYID(id);
                    this.$router.push("/datacenter");
                  }
                }
              }
            });
          } else {
            return false;
          }
        }
      }
    },

    async printCity(name, id) {
      this.mapBottle.clear();
      this.mapBottle.showLoading({
        text: "",
        color: "#01E2F7",
        maskColor: "rgba(255, 255, 255, .1)",
        zlevel: 10
      });
      const { data } = await getVideoCity(id);
      this.isChina = false;
      const {
        currMonthUseTotal,
        powerRate,
        topList,
        currMonthUseArray,
        lastMonthUseArray,
        deviceTotal,
        deviceOnlineSize,
        deviceOfflineSize,
        todayUsePowerList,
        exceptionList
      } = (this.cityInfo = data);
      const option = { ...config };
      const companylist = (this.companyList = data.companyList);
      const firstCompany = companylist ? companylist[0] : null;
      if (!firstCompany) {
        this.mapBottle.hideLoading();
        this.leftBockInfo = {};
        this.rightBlockInfo = {};
        return false;
      }
      const allCompany = companylist.map(item => ({
        name: item.name,
        value: [item.lng, item.lat, 40],
        symbolSize: 18,
        itemStyle: {
          normal: {
            color: item.state == 1 ? "#0AF046" : "red"
          }
        }
      }));
      option.geo.map = name;
      option.geo.center = [firstCompany["lng"], firstCompany["lat"]];
      option.tooltip = {
        trigger: "item",
        extraCssText: "z-index:100",
        backgroundColor: "rgba(12, 204, 104, 0.5)",
        formatter: params => params.name
      };
      option.geo.left = "center";
      option.geo.zoom = 2.1;
      option.series = [];
      const series = [
        {
          name: "企业名称",
          type: "effectScatter",
          coordinateSystem: "geo",
          data: allCompany,
          hoverAnimation: true,
          zlevel: 2,
          rippleEffect: {
            brushType: "stroke"
          },
          label: {
            normal: {
              formatter: "{b}",
              position: "right",
              show: true
            }
          },
          showEffectOn: "render"
        }
      ];
      option.series = series;
      this.mapBottle.setOption(option);
      this.mapBottle.hideLoading();
      this.leftBockInfo = {
        currMonthUseTotal,
        powerRate,
        topList,
        currMonthUseArray,
        lastMonthUseArray
      };
      this.rightBlockInfo = {
        deviceTotal,
        deviceOnlineSize,
        deviceOfflineSize,
        todayUsePowerList,
        exceptionList
      };
    },

    triggerLogout() {
      // this.$notice('123')
      // alarm = this.$alarm()
      // return false
      this.$Modal.confirm({
        title: "提示",
        content: "<p>即将退出</p><p>是否继续？</p>",
        onOk: () => {
          this.logout().then(() => {
            this.$Message.info("退出登录");
            setTimeout(() => {
              location.reload();
            }, 300);
          });
        },
        onCancel: () => {
          return false;
        }
      });
    },

    triggerAdmin() {
      // if (alarm) {
      //   alarm.close()
      // }
      // return false
      if (this.rname === "ROLE_DEMO") {
        return false;
      } else {
        this.$router.push("/company");
      }
    }
  }
};
</script>
